import java.sql.*;
import java.text.SimpleDateFormat;


public class DBTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {		
		Connection conn = null;
		long startTime = System.currentTimeMillis();
		
		try {
			System.out.println("Trying to connect to the database...");
			// Load the JDBC driver
			Class.forName ("com.mysql.jdbc.Driver").newInstance();
			
			// Create a connection to the database
			String serverName = "mysql300.ixwebhosting.com";
			String mydatabase = "bnahill_ace";
			String url = "jdbc:mysql://" + serverName +  "/" + mydatabase;
			String username = "bnahill_ace";
			String password = "aceace";
			
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			System.out.println("Could not find database driver!");
		} catch (SQLException e) {
			System.out.println("Could not connect to the database!");
		} catch (InstantiationException e) {
			System.out.println("Instantiation Exception error!");
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			System.out.println("Illegal Access Exception error!");
			e.printStackTrace();
		}
		
		try {
			Statement s = conn.createStatement();
			s.executeQuery ("SELECT * FROM prices ORDER BY time DESC LIMIT 100");
			ResultSet rs = s.getResultSet();
			SimpleDateFormat d = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
			
			while (rs.next ()) {
				int id = rs.getInt ("id");
				String cur1 = rs.getString ("cur1");
				String cur2 = rs.getString ("cur2");
				
				float buy = rs.getFloat("buy");
				float sell = rs.getFloat("sell");
				
				String date = d.format(new Date(rs.getLong("time")*1000));
				
				System.out.print("id = "+id+"\tcur1 = "+cur1+"\tcur2 = "+cur2+"\tbuy = "+buy);
				
				if (cur1.equals("JPY")) {
					if (Float.toString(buy).length() > 9)
						System.out.print("\tsell = "+sell);
					else
						System.out.print("\t\tsell = "+sell);
					
					if (Float.toString(sell).length() > 8)
						System.out.println("\ttime = "+date);
					else
						System.out.println("\t\ttime = "+date);
				} else {
					System.out.println("\t\tsell = "+sell+"\t\ttime = "+date);
				}
	       }
		} catch (SQLException e) {
			System.out.println("SQL Exception error!");
			e.printStackTrace();
		}
		
		try {
			conn.close();
			System.out.println ("Database connection terminated");
		} catch (Exception e) { /* ignore close errors */ }
		System.out.println("EXEC TIME (ms) = "+(System.currentTimeMillis()-startTime));
	}

}
